package com.example.subject10mvn.controller;


import com.example.subject10mvn.entity.Subject;
import com.example.subject10mvn.responsitory.SubjectResponsitory;
import com.example.subject10mvn.service.SubjectService;
import com.example.subject10mvn.vo.PageAndSubjects;
import com.example.subject10mvn.vo.Pagination;
import com.example.subject10mvn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/subject")
@CrossOrigin
public class SubjectController {
    @Autowired
    SubjectService subjectService;

    //插入某个题目
    @PostMapping("/")
    public Result<Object> insertOne(@RequestBody Subject subject){
        subjectService.insertOne(subject);
        return Result.builder().code("200").data(subject).build();
    }

    //删除某个题目
    @DeleteMapping("/{id}")
    public Result<Object> deleteOne( @PathVariable Integer id){

        subjectService.deleteOne(id);
        return Result.builder().code("200").build();
    }

    //更新某个题目
    @PutMapping("/")
    public Result<Object> updateOne(@RequestBody Subject subject){
        subjectService.updateOne(subject);
        return Result.builder().code("200").build();
    }

    //根据id获取某个题目
    @GetMapping("/{id}")
    public Result<Object> getOne(@PathVariable("id") Integer id){
        Subject subject=subjectService.getOne(id);
        return Result.builder().code("200").data(subject).build();
    }


    //获取所有题目
    /*
    @Param pagination 与分页相关的信息，pagination的成员变量page必须从0开始，也就是第一页时page=0
    @Param subjectTypeId 查找的分类
     */
    @GetMapping("/")
    public Result<Object> getAll(Pagination pagination,Integer subjectTypeId){

        if(pagination.getPage()==null){
            pagination.setPage(0);
        }
        if(pagination.getLimit()==null){
            pagination.setLimit(10);
        }
        if(subjectTypeId==null){
            subjectTypeId=0;
        }

        Map<String,Object> map = new HashMap<>();
        List<Subject> subjects = subjectService.findAllWithPageAndSubjectTypeId(pagination,subjectTypeId);
        map.put("subjects",subjects);
        Long total = Long.decode(subjectService.getFindAllDataTotal(pagination,subjectTypeId));
        pagination.setTotal(total);
        map.put("page",pagination);

        return Result.builder().code("200").data(map).build();
    }




}
